
export default{

  namespaced: true,

  // 模块的 state 数据
  state: () => ({
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_icon, goods_state }
    cartList: JSON.parse(uni.getStorageSync('cart')||'[]')
  }),

  // 模块的 mutations 方法
  mutations: {
	  addToCart(state,goods){
		  const findResult = state.cartList.find(x=>x.goods_id==goods.goods_id)
		  if(findResult){
			  findResult.goods_count++
		  }else{
			  state.cartList.push(goods)
		  }
		  this.commit('cart/saveToStorage')
	  },
	  saveToStorage(state){
		  uni.setStorageSync('cart',JSON.stringify(state.cartList))
	  },
	  updateCartState(state,goods){
		  const findResult = state.cartList.find(x=>x.goods_id==goods.goods_id)
		  if(findResult){
			  findResult.goods_state = goods.goods_state
		  }
		  this.commit('cart/saveToStorage')
	  },
	  updateCartCount(state,goods){
		  const findResult = state.cartList.find(x=>x.goods_id==goods.goods_id)
		  if(findResult){
			  findResult.goods_count=goods.goods_count
		  }
		  this.commit('cart/saveToStorage')
	  },
	  deleteCartById(state,goods_id){
		  state.cartList = state.cartList.filter(x=>x.goods_id!=goods_id)
		  this.commit('cart/saveToStorage')
	  },
	  switchAllCartState(state,checked){
	  		state.cartList.forEach((x)=>{
				x.goods_state = checked
			})
	  		this.commit('cart/saveToStorage')
	  },
  },

  // 模块的 getters 属性
  getters: {
	  total(state){
		  let c = 0
		  state.cartList.forEach((x)=>{
			c+=x.goods_count
		  })
		  return c
	  },
	  checkedCount(state){
		  return state.cartList.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
	  },
	  totalPrice(state){
		  let d = 0
		  state.cartList.forEach((x)=>{
				if(x.goods_state){
					d+=x.goods_price*x.goods_count
				}
		  })
		  return d
	  }
  },
}